package org.tong.database.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.tong.bean.Teacher;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class TeacherTemplateDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Teacher> queryAllTeachers() {
        return jdbcTemplate.query("select * from teacher", new RowMapper<Teacher>() {
            @Override
            public Teacher mapRow(ResultSet resultSet, int i) throws SQLException {
                Teacher teacher = new Teacher();
                teacher.setId(resultSet.getInt(1));
                teacher.setName(resultSet.getString(2));
                teacher.setNo(resultSet.getInt(3));
                return teacher;
            }
        });
    }

    public int insert(Teacher teacher) {
        Assert.notNull(teacher.getName(), "teacer.name can not be null");
        return jdbcTemplate.update("insert into teacher(name,no)values(?,?)", teacher.getName(), teacher.getNo());
    }

}
